package com.boot2.core;

import java.util.Stack;

/**
 * @author zhangweilin
 * @Description: 当前线程调用计数
 * @date 2019/10/12
 */
public class MethodCallCounter {

    /**
     * 调用堆栈计数
     */
    private ThreadLocal<Stack<Integer>> callCounter = new ThreadLocal<>();

    /**
     * 方法调用
     */
    public void call() {
        Stack<Integer> stack = getStack();
        stack.push(1);
        return;
    }

    /**
     * 返回后调用
     * @return
     */
    public int returned() {
        Stack<Integer> stack = getStack();
//        int size = stack.size();
        Integer count = null;
        try {
            count = stack.pop();
        } catch (Exception e) {
//            e.printStackTrace();
            return 0;
        }
        return stack.size();
    }

    /**
     * 获取堆栈
     * @return
     */
    private Stack<Integer> getStack() {
        Stack<Integer> stack = callCounter.get();
        if (null == stack) {
            stack = new Stack<>();
            callCounter.set(stack);
//            stack.push(1);
        }
        return stack;
    }


    /**
     * 清空
     */
    public void clear() {
        callCounter.remove();
    }

}
